<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>产品添加</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
	<link rel="stylesheet" href="/plugins/layui/css/layui.css" media="all" />
	<link rel="stylesheet" href="/css/productsAdd.css" media="all" />
</head>
<body class="childrenBody">
	<form class="layui-form" style="padding: 20px;">
		<div class="form-header">
			<ul>
				<li>
					<label class="layui-form-label">产品类别</label>
					<div class="layui-input-block">
						<select name="categoryId" lay-verify="required" id="categoryId">
							<option value="">--请选择产品类别--</option>
						</select>
					</div>
				</li>
				<li>
					<label class="layui-form-label">产品名称</label>
					<div class="layui-input-block">
						<input type="text" class="layui-input" lay-verify="required" name="name" placeholder="请输入产品名称" id="productName">
					</div>
				</li>
				<li>
					<label class="layui-form-label">产品价格</label>
					<div class="layui-input-block">
						<input type="number" class="layui-input" id="productPrice" lay-verify="required||number" name="price" placeholder="请输入产品价格">
					</div>
				</li>
				<li>
					<label class="layui-form-label">产品说明</label>
					<div class="layui-input-block">
						<input type="text" id="productMsg" class="layui-input" lay-verify="required" name="description" placeholder="请输入产品说明">
					</div>
				</li>
				<li>
					<label class="layui-form-label">平均耗时</label>
					<div class="layui-input-block">
						<select name="categoryId" lay-verify="required" id="productTime">
							<option value="">--请选择平均耗时--</option>
							<option value="10">10分钟</option>
							<option value="20">20分钟</option>
							<option value="30">30分钟</option>
							<option value="40">40分钟</option>
							<option value="50">50分钟</option>
							<option value="60">60分钟</option>
							<option value="70">70分钟</option>
							<option value="80">80分钟</option>
							<option value="90">90分钟</option>
						</select>
					</div>
				</li>
			</ul>
		</div>
		<div class="table" id="form-list">
			<table class="layui-table" lay-filter="info" id="info-list">

			</table>
		</div>
		<div class="add-footer">
			<div class="add" id="add-list">添加</div>
			<div class="save" id="save">保存</div>
		</div>
	</form>
	<script type="text/javascript" src="/js/jquery-1.11.2.min.js"></script>
	<script type="text/javascript" src="/plugins/layui/layui.js"></script>
	<script type="text/html" id="delDemo">
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon"></i>删除</a>
	</script>
	<script type="text/javascript">
        layui.use('table', function(){
            var table = layui.table;
            var tabledata = [];
            $(".save1").click(function () {
                console.dir(tabledata );
				//alert(tabledata)
            });
            //第一个实例
            table.render({
                elem: '#info-list'
                ,data: tabledata
                ,page: false //开启分页
                ,cols: [[ //表头
                    {field: 'sort', title: '排序(必填)', sort: true, fixed: 'left',edit: 'text'}
                    ,{field: 'name', title: '工序名称(必填)', edit: 'text'}
                    ,{field: 'description', title: '介绍(选填)',edit: 'text'}
                    ,{title: '操作', align:'center', toolbar: '#delDemo'}
                ]]
				,limit:100
            });
            //监听单元格编辑
            table.on('edit(info)', function(obj){

                var value = obj.value //得到修改后的值
                    ,data = obj.data //得到所在行所有键值
                    ,field = obj.field; //得到字段
                var d;
                var reg = /^[1-9]\d*$/;

                if(data.sort!=''){
                    var oldValue=$(this).prev().text();
                    if(!reg.test(obj.data.sort)){
                        obj.data.sort=oldValue;
                        table.reload('info-list',{
                            data : tabledata
                        });
                        layer.msg("顺序请输入正整数")
                    }
				}
                tabledata[data.LAY_TABLE_INDEX] = data;
            });
            /**
			 * 删除某一行
			 * **/
            table.on('tool(info)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                var data = obj.data; //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                var tr = obj.tr; //获得当前行 tr 的DOM对象
                console.log(tr.selector);
                if(layEvent === 'detail'){ //查看
                    //do somehing
                } else if(layEvent === 'del'){ //删除
                    layer.confirm('真的删除行么', function(index){
						let str = tr.selector.split('"');
                        tabledata.splice(parseInt(str[1]),1);
                        table.reload('info-list',{
                            data : tabledata
                        });
                        layer.close(index);
                        //向服务端发送删除指令
                    });
                } else if(layEvent === 'edit'){ //编辑
                    //do something

                    //同步更新缓存对应的值
                    obj.update({
                        username: '123'
                        ,title: 'xxx'
                    });
                }
            });
			/**
			 * 动态添加列表
			 * **/
            $("#add-list").click(function(){
                console.log(tabledata);
                var data1={"sort":"","name":"","description":""};
                tabledata.push(data1);
                table.reload('info-list',{
                    data : tabledata
                });
            })
            /**
             * 保存
             * **/
            $("#save").bind("click",function(){
                var obj = {}
                if($("#categoryId").val() == ""){
                    layer.msg('请选择产品类别');
                    return;
                }else if($("#productName").val() ==""){
                    layer.msg('请输入产品名称');
                    return;
                }else if($("#productPrice").val() == ""){
                    layer.msg('请输入产品价格');
                    return;
                }else if($("#productMsg").val() ==""){
                    layer.msg('请输入产品说明');
                    return;
                }else if($("#productTime").val() == ""){
                    layer.msg('请选择消耗时间');
                    return;
                }
                obj.categoryId = parseInt($("#categoryId").val());
                obj.name = $("#productName").val();
                obj.price = parseInt($("#productPrice").val());
                obj.description = $("#productMsg").val();
                obj.consumeTime = $("#productTime").val();
                for(var i in tabledata){

                    if(tabledata[i].sort==''){
                        layer.msg('请填写工序顺序');
                        return;
					}else if(tabledata[i].name==''){
                        layer.msg('请填写工序名称');
                        return;
					}else if(tabledata[i].name.length>20){
                        layer.msg('名称最多20个字符');
                        return;
					}
				 tabledata[i].sort = parseInt(tabledata[i].sort);
				}
                obj.workstageList = tabledata;
                console.log(obj)
                var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
                $.ajax({
                    type: "POST",
					data:JSON.stringify(obj),
                    url:"/products",
                    contentType : 'application/json',
                    success: function(result) {
                        console.log(result);
                        if(result.code==2000){
                              top.layer.close(index);
								top.layer.msg("添加成功！");
								top.layer.closeAll("iframe");
								parent.location.reload();
                        }else{
                            top.layer.msg(result.msg);
                        }
                    } ,
                    error: function(request) {
                        alert("Connection error");
                    }
                });
            })
        });
	  var categorysList;
	  $.ajax({
          type : "GET",
          url: '/categorys/getAllCategorys',
          dataType:'json',
       	  async:false,
          success: function(data){
          	var list=data.data;
          	regionsList=list;
          	var html='';
              for(var i=0;i<list.length;i++){	
                  html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>"
              }
              $("#categoryId").append(html);
          }
      });
	
	layui.config({
		base : "js/"
	}).use(['form','layer','jquery'],function(){
		var form = layui.form,
			layer = parent.layer === undefined ? layui.layer : parent.layer,
			$ = layui.jquery;
	 	form.on("submit(addProducts)",function(data){
	 		var datas=data.field;
	 		var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
	 		$.ajax({  
	            type: "POST",  
	            url:"/products",  
	            data:JSON.stringify(datas),// 序列化表单值
	            contentType:"application/json",
	            success: function(data) { 
	            	if(data.code==2000){
	            		top.layer.close(index);
	          			top.layer.msg("添加成功！");
	           			layer.closeAll("iframe");
	          	 		//刷新父页面
	          	 		parent.location.reload();
	            	}
	            } ,
		 		 error: function(request) {  
		             alert("Connection error");  
		         } 
	        }); 
	 		return false;
	 	})
		
	})

	</script>
</body>
</html>

